
type FormatKeys = 'YY' | 'MM' | 'DD' | 'hh' | 'mm' | 'ss'

/**
 * 最简时间格式化工具
 * @param {Date} date 日期
 * @param {string} format 格式 如：YYYY-MM-DD hh:mm:ss
 * @returns string
 */
export function formatDate(format: string, date = new Date()) {
  if (!(date instanceof Date)) {
    throw new TypeError('请传递正确的Date对象')
  }

  const o = {
    YY: date.getFullYear(),
    MM: date.getMonth() + 1,
    DD: date.getDate(),
    hh: date.getHours(),
    mm: date.getMinutes(),
    ss: date.getSeconds(),
  }

  return Object.keys(o).reduce((pre, key) => {
    const v = o[key as FormatKeys]
    return (pre = pre.replace(key, v < 10 ? `0${v}` : String(v)))
  }, format)
}

/**
 * 预加载一些页面
 * @param {string[]} urls
 */
export function preLoadPages(urls: string[]) {
  urls.forEach((url) => {
    uni.preloadPage({ url })
  })
}

/**
 * 格式化金额
 */
export function formatMoney(money: number | string, fixed = 0) {
  if (typeof money === 'string') {
    money = Number(money.trim())
  }
  if (Number.isNaN(money)) { return '0.00' }
  return (money / 100).toFixed(fixed)
}

/**
 * 获取图片高宽比
 */
export function getImageRatio(url: string) {
  return new Promise<{ width: number, height: number, aspectRatio: number }>((resolve) => {
    uni.getImageInfo({
      src: url,
      success: (res) => {
        // 获取图片的宽度和高度
        const width = res.width
        const height = res.height
        // 计算高宽比
        const aspectRatio = height / width
        resolve({ width, height, aspectRatio })
      },
      fail: () => {
        resolve({ width: 0, height: 0, aspectRatio: 1 })
      },
    })
  })
}

export function formatTime(format: string, time: number) {
  const o = {
    DD: Math.floor(time / (24 * 3600)),
    hh: Math.floor((time % (24 * 3600)) / 3600),
    mm: Math.floor((time % 3600) / 60),
    ss: Math.floor(time % 60),
  }

  return Object.keys(o).reduce((pre, key) => {
    const v = o[key as 'DD' | 'hh' | 'mm' | 'ss']
    return (pre = pre.replace(key, v < 10 ? `0${v}` : String(v)))
  }, format)
}
